
import { SceneBase } from "../../cccframework/Common/Components/SceneBase";
import UITouchScript from "../../cccframework/Common/Components/UITouchScript";
import { gameHelper } from "../../cccframework/Utils/GameHelpler";
import eventMgr from "./EventMgr";
import GameClient, { Frame } from "./GameClient";
import RemoteSensingControl from "./RemoteSensingControl";

const { ccclass, property } = cc._decorator;

@ccclass
export default class netWorkGame extends SceneBase {

    @property(cc.Label)
    tip: cc.Label = null;
    @property(cc.Node)
    matchBtn: cc.Node = null;
    @property(cc.Node)
    gameOverBtn: cc.Node = null;
    @property(RemoteSensingControl)
    remoteCtrl: RemoteSensingControl = null;

    isOperationed: boolean = false;
    totalFrames = [];
    curframes = [];
    roleName: string = 'default';
    curRunFrameIdx: number = 0;
    frameRate: number = 64;

    onLoad() {
        super.onLoad && super.onLoad();
        this.tip.string = '登录中'
        UITouchScript.getUICameraTouchScript()
        GameClient.instance.init()
        // GameClient.instance.on('')
        eventMgr.on(GameClient.instance, 'onLogin', this.onLogin, this);
        eventMgr.on(GameClient.instance, 'onMatchSuccess', this.onMatchSuccess, this);
        eventMgr.on(GameClient.instance, 'onUpdate', this.onUpdate, this);

    }

    onLogin() {
        this.tip.string = '登录完成'
        // GameClient.instance.match.call(GameClient.instance);
        this.scheduleOnce(() => {
            this.tip.string = '账号：' + GameClient.instance.token;
        }, 1)
        this.roleName = GameClient.instance.token.substr(0, 6);
        this.matchBtn.on(cc.Node.EventType.TOUCH_END, GameClient.instance.match, GameClient.instance);

        // 添加定期指令
        this.schedule(() => {
            this.sendMoveCmd();
        }, 1 / this.frameRate)
    }

    onMatchSuccess(event: string) {
        this.matchBtn.active = false;
        console.log('onMatchSuccess', event)
        GameClient.instance.send({
            type: 'cmd',
            func: 'createRole',
            argv: [
                this.roleName,
                gameHelper.randomInteger(-cc.winSize.width / 2 * 0.9, cc.winSize.width / 2 * 0.9),
                gameHelper.randomInteger(-cc.winSize.width / 2 * 0.9, cc.winSize.width / 2 * 0.9),
            ]
        })
        this.gameOverBtn.on(cc.Node.EventType.TOUCH_END, this.gameOver, this)
        this.gameOverBtn.on(cc.Node.EventType.TOUCH_END, this.gameOver, this)
    }

    onMatchFail() {
        this.matchBtn.active = true;
    }

    createRole(roleName: string, x: number, y: number) {
        if (!cc.find('Canvas/game/' + roleName)) {
            let role = new cc.Node(roleName);
            role.parent = cc.find('Canvas/game')
            role.position = cc.v2(x, y);
            let label = role.addComponent(cc.Label)
            label.string = roleName;
        }
    }
    dstPos: { [role: string]: cc.Vec2 } = {}
    moveRole(roleName: string, x: number, y: number) {
        let role = cc.find('Canvas/game/' + roleName)
        this.dstPos[roleName] = this.dstPos[roleName] || role.position
        this.dstPos[roleName] = this.dstPos[roleName].add(cc.v2(x, y));
        // role.position = role.position.add(cc.v2(x, y));
        // role.position = role.position.lerp(role.position.add(cc.v2(x, y)), this.dt * 5)
    }

    gameOver() {

    }

    sendMoveCmd() {
        if (this.remoteCtrl && !this.remoteCtrl.moveDir.equals(cc.v2())) {
            let dist = this.moveSpeed * (1 / this.frameRate);
            console.log('dist', ~~(this.remoteCtrl.moveDir.x * dist))
            console.log('dist2', ~~(this.remoteCtrl.moveDir.y * dist))
            GameClient.instance.send({
                type: 'cmd',
                func: 'moveRole',
                argv: [
                    this.roleName,
                    ~~(this.remoteCtrl.moveDir.x * dist),
                    ~~(this.remoteCtrl.moveDir.y * dist),
                ]
            })
        }
    }

    updateLogicFrame() {
        for (let i = 0; i < this.logicUpdateNumPerFrame; i++) {
            if (this.curRunFrameIdx < this.totalFrames.length) {
                let frame = <Frame>this.totalFrames[this.curRunFrameIdx]
                if (frame && frame.cmds) {
                    console.log('this.curRunFrameIdx', this.curRunFrameIdx)
                    frame.cmds.forEach(cmd => {
                        if (cmd) {
                            this[cmd.func].apply(this, cmd.argv);
                            console.log('cmd.func', cmd.func)
                        }
                    })
                    this.curRunFrameIdx++;
                }
            }
        }
    }

    /**更新逻辑帧 */
    onUpdate(event: string) {
        // console.log('onFrame', event)
        this.curframes.push(event)
        this.totalFrames.push(event)
    }
    moveSpeed: number = 500;
    dt: number = 0;
    logicUpdateNumPerFrame: number = 1;
    update(dt: number) {
        this.dt = dt;
        // this.sendMoveCmd();
        this.updateLogicFrame()
        for (let roleName in this.dstPos) {
            let role = cc.find('Canvas/game/' + roleName)
            // let dir = this.dstPos[roleName].sub(role.position);
            // let dist = this.dt * 100 < dir.mag()
            // role.position = dir.mul(this.dt * 100)
            // role.position = this.dstPos[roleName]
            role.position = role.position.lerp(this.dstPos[roleName], this.dt * 15)
        }

    }


    move(touch: cc.Event.EventTouch) {
        console.log('move')

    }
}
